//
//  LWColumnShapeView.swift
//  LWColumnShapeView
//
//  Created by 赖灵伟 on 15/10/27.
//  Copyright © 2015年 深圳创世易明科技有限公司. All rights reserved.
//

import UIKit

@IBDesignable
class LWColumnShapeView: UIView {

    // ========== Public ==========
    
    /**底色*/
    @IBInspectable var trackColor: UIColor = UIColor(red: 255.0 / 255.0, green: 255.0 / 255.0, blue: 255.0 / 255.0, alpha: 0.1) {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /**填充颜色*/
    @IBInspectable var fillColor: UIColor = UIColor(red: 240.0 / 255.0, green: 213.0 / 255.0, blue: 117.0 / 255.0, alpha: 1.0) {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /**标题颜色*/
    @IBInspectable var titleColor: UIColor = UIColor.whiteColor() {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /**标题字体*/
    @IBInspectable var titleFont: CGFloat = 12.0 {
        didSet {
            setNeedsDisplay()
        }
    }
    
    // ========== Private ==========
    
    /**图表离顶部距离*/
    private let topSpace: CGFloat = 10.0
    
    /**满值点与图表顶部距离*/
    private let fullToTableTopSpace: CGFloat = 90.0

    /**表格间隙*/
    private let space: CGFloat = 3.0
    
    /**选中视图*/
    private lazy var selectedView: LWColumnSelectedView = {
        let lineWidth: CGFloat = (self.frame.size.width - self.space * CGFloat(self.titleAry.count - 1)) / CGFloat(self.titleAry.count)
        let view = LWColumnSelectedView(frame: CGRectMake(0, 0, lineWidth, self.frame.size.height))
        
        return view
    }()
    
    private var selectedHandler: ((index: Int, name: String, score: CGFloat, level: Int, title: String) -> Void)?
    
    
    // ========== Values ==========
    
    /**标题*/
    private var titleAry: [String] = ["测绘知识", "成功学", "道教知识", "地理知识", "公共知识"] {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /**评分*/
    private var scoreAry: [CGFloat] = [0.3, 0.2, 0.5, 0.9, 0.4] {
        didSet {
            setNeedsDisplay()
        }
    }
    
    
    private var maxValue: CGFloat = 100.0
    private var originalScoreAry: [CGFloat] = [30, 20, 50, 90, 40] {
        didSet {
            scoreAry.removeAll()
            var ary = [CGFloat]()
            for i in 0..<originalScoreAry.count {
                let value = originalScoreAry[i] / maxValue > 1 ? 1 : originalScoreAry[i] / maxValue
                ary.append(value)
            }
            scoreAry = ary
        }
    }
    
    
    
    // MARK: - Life cycle
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clearColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        backgroundColor = UIColor.clearColor()
    }
    
    
    
    
    override func drawRect(rect: CGRect) {
        
        // 线宽
        let count = titleAry.count == 0 ? 1 : titleAry.count
        let lineWidth: CGFloat = (frame.size.width - space * CGFloat(count - 1)) / CGFloat(count)
        
        // 1、Draw TrackLayer
        trackColor.setStroke()
        let trackBeziPath = UIBezierPath()
        trackBeziPath.lineWidth = lineWidth
        for i in 0..<count {
            let x: CGFloat = (lineWidth + space) * CGFloat(i) + lineWidth / 2
            trackBeziPath.moveToPoint(CGPointMake(x, frame.size.height))
            trackBeziPath.addLineToPoint(CGPointMake(x, topSpace))
            trackBeziPath.closePath()
        }
        trackBeziPath.stroke()
        
        // 2、Draw FillLayer
        fillColor.setStroke()
        let fillBeziPath = UIBezierPath()
        fillBeziPath.lineWidth = lineWidth
        for i in 0..<count {
            let x: CGFloat = (lineWidth + space) * CGFloat(i) + lineWidth / 2
            var score = scoreAry[i] ?? 0
            if score < 0 {
                score = 0
            } else if score > 1 {
                score = 1
            }
            fillBeziPath.moveToPoint(CGPointMake(x, frame.size.height))
            fillBeziPath.addLineToPoint(CGPointMake(x, frame.size.height - (frame.size.height - topSpace - fullToTableTopSpace) * score))
            fillBeziPath.closePath()
        }
        fillBeziPath.stroke()
        
        // 3、Draw Titles
        for i in 0..<count {
            let titleStr = NSString(string: titleAry[i])
            
            let frame = CGRectMake((lineWidth + space) * CGFloat(i), 8 + topSpace, lineWidth - 8, 30)
            let style = NSMutableParagraphStyle()
            style.alignment = NSTextAlignment.Right
            titleStr.drawInRect(frame, withAttributes: [
                NSFontAttributeName : UIFont.boldSystemFontOfSize(titleFont),
                NSForegroundColorAttributeName : titleColor,
                NSParagraphStyleAttributeName : style])
            
        }
        
        
        
        
    }
    
    
    // MARK: - Public
    
    func show(titleAry titleAry: [String], scoreAry: [CGFloat], maxValue: CGFloat, animation: Bool, selectedIndex: Int) {
        
        self.titleAry = titleAry
        self.maxValue = maxValue
        self.originalScoreAry = scoreAry
        
        let tmpScoreAry = self.scoreAry
        
        if animation {
            userInteractionEnabled = false
            self.scoreAry.removeAll()
            for _ in 0..<scoreAry.count {
                self.scoreAry.append(0.0)
            }
            updateValueBy(0.05, maxValues: tmpScoreAry, index: 0)
        }
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            NSThread.sleepForTimeInterval(2)
            dispatch_async(dispatch_get_main_queue()) {
                self.selectedIndex = selectedIndex
                self.selectedWithIndex(selectedIndex)
            }
        }
        
        
    }
    
    /**点击回调*/
    func didSelectedHandler(hander: ((index: Int, name: String, score: CGFloat, level: Int, title: String) -> Void)?) {
        selectedHandler = hander
    }
    
    
    
    // MARK: - Touch methods
    
    private var selectedIndex: Int = 0
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        
        let touch = touches.first!
        let localPoint: CGPoint = touch.locationInView(self)
        
        // outside content
        if localPoint.y < topSpace {
            return
        }
        
        // fetch index
        let count = titleAry.count == 0 ? 1 : titleAry.count
        let lineWidth: CGFloat = (frame.size.width - space * CGFloat(count - 1)) / CGFloat(count)
        selectedIndex = Int(localPoint.x / lineWidth)
        
    }
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesEnded(touches, withEvent: event)
        
        let touch = touches.first!
        let localPoint: CGPoint = touch.locationInView(self)
        
        // outside content
        if localPoint.y < topSpace {
            return
        }
        
        // fetch index
        let count = titleAry.count == 0 ? 1 : titleAry.count
        let lineWidth: CGFloat = (frame.size.width - space * CGFloat(count - 1)) / CGFloat(count)
        let index: Int = Int(localPoint.x / lineWidth)
        selectedWithIndex(index)
        
//        if selectedIndex != index {
//            return
//        }
//        if selectedIndex >= titleAry.count {
//            selectedIndex = titleAry.count - 1
//        }
//        
//        let position: CGPoint = CGPointMake((lineWidth + space) * CGFloat(selectedIndex) + lineWidth / 2, frame.size.height / 2)
//        
//        // Fetch Level and Title
//        let level = LWHelper.fetchLevel(originalScoreAry[selectedIndex])
//        let title = LWHelper.fetchTitle(titleAry[selectedIndex], level: level)
//        
//        // Show
//        let fillHeight = (frame.size.height - topSpace - fullToTableTopSpace) * scoreAry[selectedIndex]
//        selectedView.show(self, position: position, name: titleAry[selectedIndex], scoreText: String(Int(originalScoreAry[selectedIndex])) + ", LV\(level)", title: title, fullColorHegith: fillHeight, fullColor: fillColor)
//        
//        // Hanlder
//        selectedHandler?(index: selectedIndex, name: titleAry[selectedIndex], score: originalScoreAry[selectedIndex], level: level, title: title)
    }
    
    
    
    // MARK: - Helper methods
    
    // MARK: - Helper methods
    
    private func selectedWithIndex(index: Int) {
        
        // fetch index
        let count = titleAry.count == 0 ? 1 : titleAry.count
        let lineWidth: CGFloat = (frame.size.width - space * CGFloat(count - 1)) / CGFloat(count)
        if selectedIndex != index {
            return
        }
        if selectedIndex >= titleAry.count {
            selectedIndex = titleAry.count - 1
        }
        
        let position: CGPoint = CGPointMake((lineWidth + space) * CGFloat(selectedIndex) + lineWidth / 2, frame.size.height / 2)
        
        // Fetch Level and Title
        let level = LWHelper.fetchLevel(originalScoreAry[selectedIndex])
        let title = LWHelper.fetchTitle(titleAry[selectedIndex], level: level)
        
        // Show
        let fillHeight = (frame.size.height - topSpace - fullToTableTopSpace) * scoreAry[selectedIndex]
        selectedView.show(self, position: position, name: titleAry[selectedIndex], scoreText: String(Int(originalScoreAry[selectedIndex])) + "分", title: title, fullColorHegith: fillHeight, fullColor: fillColor)
        
        // Hanlder
        selectedHandler?(index: selectedIndex, name: titleAry[selectedIndex], score: originalScoreAry[selectedIndex], level: level, title: title)
    }
    
    /**递归*/
    private func updateValueBy(delta: CGFloat, maxValues: [CGFloat], index: Int) {
        
        // 在当前index下，最大值值
        let perMaxValue: CGFloat = maxValues[index]

        // 拿出每一个数值
        var currentValue: CGFloat = scoreAry[index]
        
        // +1
        currentValue += delta
        if currentValue > perMaxValue {
            currentValue = perMaxValue
        }

        // 重新放入原数组
        scoreAry[index] = currentValue
        
        // 每次等待时间
        if currentValue >= perMaxValue {
            if index + 1 < maxValues.count {
                // 下一个index递归
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                    NSThread.sleepForTimeInterval(NSTimeInterval(0.03))
                    dispatch_async(dispatch_get_main_queue()) {
                        self.updateValueBy(delta, maxValues: maxValues, index: index + 1)
                    }
                }
            } else {
                userInteractionEnabled = true
                return
            }
        } else {
            // 当前index递归
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                NSThread.sleepForTimeInterval(NSTimeInterval(0.03))
                dispatch_async(dispatch_get_main_queue()) {
                    self.updateValueBy(delta, maxValues: maxValues, index: index)
                }
            }
            
        }
        
        
    }
    
    

}



private class LWColumnSelectedView: UIView {
    
    private let nameLabel: UILabel = UILabel()
    private let scoreLabel: UILabel = UILabel()
    private let titleLabel: UILabel = UILabel()
    
    private let fullView: UIView = UIView(frame: CGRectZero)
    
    private let titleFont: CGFloat = 13.0
    private let subTitleFont: CGFloat = 11.0
    
    // Life cycle
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.shadowOpacity = 0.4
        layer.shadowOffset = CGSizeMake(2, 1)
        configueSubViews()
        userInteractionEnabled = false
        backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configueSubViews() {
        
        addSubview(fullView)
        
        nameLabel.frame = CGRectMake(0, 8, frame.size.width, 24)
        nameLabel.textAlignment = NSTextAlignment.Center
        nameLabel.font = UIFont.boldSystemFontOfSize(titleFont)
        nameLabel.textColor = UIColor.darkGrayColor()
        addSubview(nameLabel)
        
        scoreLabel.frame = CGRectMake(3, 8 + nameLabel.frame.size.height, frame.size.width - 6, 16)
        scoreLabel.textAlignment = NSTextAlignment.Right
        scoreLabel.font = UIFont.boldSystemFontOfSize(subTitleFont)
        scoreLabel.textColor = UIColor.darkGrayColor()
        addSubview(scoreLabel)
        
        titleLabel.frame = CGRectMake(3, 8 + scoreLabel.frame.origin.y + scoreLabel.frame.size.height, frame.size.width - 6, 16)
        titleLabel.textAlignment = NSTextAlignment.Right
        titleLabel.font = UIFont.boldSystemFontOfSize(subTitleFont)
        titleLabel.textColor = UIColor.lightGrayColor()
        addSubview(titleLabel)
        
    }
    
    
    func show(inView: UIView, position: CGPoint, name: String, scoreText: String, title: String, fullColorHegith: CGFloat, fullColor: UIColor) {
        
        layer.removeAllAnimations()
        removeFromSuperview()
        alpha = 0.0
        
        nameLabel.text = name
        scoreLabel.text = scoreText
        titleLabel.text = title
        
        fullView.backgroundColor = fullColor
        fullView.frame = CGRectMake(0, frame.size.height - fullColorHegith, frame.size.width, fullColorHegith)
        
        center = position
        inView.addSubview(self)
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            self.alpha = 1.0
            self.transform = CGAffineTransformMakeScale(1.05, 1.05)
            }) { (_) -> Void in
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    self.transform = CGAffineTransformIdentity
                })
        }
    }
    
    
}












